from django.http import HttpResponse, JsonResponse
from core.service import *
from core.log import logging
from core.config import cfg
from core.general.crypto import CRYPTO

def slat(func):
    def wapper(*args, **kwargs):
        query_params = None
        for o in args:
            if isinstance(o, Request):
                request = o
                break
        if not request:
            return JsonResponse({'state': -1, 'msg': 'not found request object.'})
        if request.method == "GET":
            query_params = request.query_params
        if request.method == "POST":
            query_params = request.data
        if query_params:
            if "sign" not in query_params:
                return JsonResponse({'state': -1, "msg": "http request query parameter not found salt key('sign'), see help /core/decorator/salt.md"})
            m_str = ''
            client_sign = query_params["sign"]
            for o in sorted(query_params):
                if o.lower() != "sign":
                    m_str += query_params[o]
            sys_d= datetime.now().strftime("%Y/%m%d")
            service_sign = CRYPTO.md5([m_str, CRYPTO.md5([cfg.APP_ID,cfg.APP_SECRET,cfg.SERVICE_KEY,cfg.SERVICE_ACCESS_SECRET,sys_d])])
            if client_sign != service_sign:
                return JsonResponse({'state': -1, 'msg': 'sign error.'})
            return func(*args,**kwargs)
        else:
            return JsonResponse({'state':500, "msg":'not found query params.'})
    return wapper
